import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Point } from "ol/geom";
import { Icon, Text, Style, Fill, Stroke } from "ol/style";
import { Feature } from "ol";
import { fromLonLat } from "ol/proj";
import { cities } from "./data";
// 天地图密钥
var key = "2b652d4e7858f5a1310620992c2cfe3c"; // 你的API Key
var siteindex = Math.round(Math.random() * 7); // 天地图的多个节点选择

// 浙江省的图层（如果你只需要浙江的区域，天地图会根据瓦片进行裁剪）
export const zhejiangLayer = new TileLayer({
  source: new XYZ({
    url: `https://t{0-7}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=${key}`,
    crossOrigin: "Anonymous",
    cacheSize: 2048,
    tileLoadFunction: function (imageTile, src) {
      imageTile.getImage().src = src; // 自定义加载函数来缓存图像
    },
    maxZoom: 18,
    zIndex: 1,
  }),
});

// 天地图影像底图图层 （卫星图层）
export const img_wLayer = new TileLayer({
  source: new XYZ({
    url: "https://t" + siteindex + ".tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + key,
    crossOrigin: "Anonymous",
    cacheSize: 2048, // 提高缓存容量
    tileSize: 512, // 调整瓦片大小（增加瓦片尺寸，减少请求次数）
    tileLoadFunction: (imageTile, src) => {
      const image = new Image();
      image.onload = () => {
        imageTile.getImage().src = image.src;
      };
      // 支持 WebP 格式
      image.src = src.replace(/\.png$/, ".webp");
    },
  }),
  title: "影像底图",
  maxZoom: 18,
  zIndex: 1,
});

export const vec_wLayer = new TileLayer({
  source: new XYZ({
    url: "https://t" + siteindex + ".tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + key,
    crossOrigin: "Anonymous",
    cacheSize: 2048, // 提高缓存容量
    // tileSize: 512, // 调整瓦片大小（增加瓦片尺寸，减少请求次数）
    tileLoadFunction: (imageTile, src) => {
      const image = new Image();
      image.onload = () => {
        imageTile.getImage().src = image.src;
      };
      // 支持 WebP 格式
      image.src = src.replace(/\.png$/, ".webp");
    },
  }),
  title: "矢量底图",
  zIndex: 1,
});

// 天地图地形图层
export const ter_wLayer = new TileLayer({
  source: new XYZ({
    url: "https://t" + siteindex + ".tianditu.gov.cn/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=" + key,
    crossOrigin: "Anonymous",
    cacheSize: 2048,
    // tileSize: 512, // 调整瓦片大小（增加瓦片尺寸，减少请求次数）
    tileLoadFunction: (imageTile, src) => {
      const image = new Image();
      image.onload = () => {
        imageTile.getImage().src = image.src;
      };
      // 支持 WebP 格式
      image.src = src.replace(/\.png$/, ".webp");
    },
  }),
  title: "地形底图",
  zIndex: 1,
});

// 定义城市名称的矢量图层
export const cityNameLayer = new VectorLayer({
  source: new VectorSource({
    features: [], // 这里存储城市名称的特征
  }),
  zIndex: 2, // 确保城市名称图层在其他图层之上
});

// 创建标注样式
const createTextStyle = (name) => {
  return new Style({
    text: new Text({
      text: name,
      font: "16px Calibri,sans-serif",
      fill: new Fill({
        color: "black",
      }),
      stroke: new Stroke({
        color: "white",
        width: 5,
      }),
      offsetX: 0,
      offsetY: 0,
    }),
  });
};

// 添加城市名称
const addCityName = (cityName, coords) => {
  const cityFeature = new Feature({
    geometry: new Point(coords), // 坐标
  });

  cityFeature.setStyle(createTextStyle(cityName)); // 设置样式
  cityNameLayer.getSource().addFeature(cityFeature); // 添加到图层中
};

// 为浙江省内的每个城市添加标注
cities.forEach((city) => {
  addCityName(city.name, city.coords);
});

// 设置默认视图时的位置和缩放级别
export const defaultView = {
  center: [119.9319, 30.6554], // 中心坐标：浙江省
  zoom: 11, // 默认缩放级别
};
